// 两根线
// 同步：组件 commit -> mutations -> state
// 异步： 组件 dispatch -> actions -> commit -> mutations -> state
import { login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'

export default {
  // 开启命名空间
  namespaced: true,
  // 放数据的地方
  state: () => ({
    token: getToken() || '',
    userinfo: {},
    routes: constantRoutes
  }),
  // 相当于组件中计算属性
  getters: {},
  // 这个是唯一修改state中数据地方
  mutations: {
    // setCount(state) {}
    setToken(state, payload) {
      state.token = payload
      setToken(payload)
    },
    // setUserInfo(state, payload) {
    //   state.userinfo = payload
    // },
    updateRoutes(state, payload) {
      state.routes = [...constantRoutes, ...payload]
    }
  },
  // 写异步的ajax的地方
  actions: {
    // store.commit()
    // getData(store){}
    async login(context, payload) {
      console.log(payload)
      const res = await login(payload)
      console.log(res)
      context.commit('setToken', res.data.data.token)
    },
    // async getInfo(context, payload) {
    //   const res = await getInfo()
    //   console.log(res)
    //   context.commit('setUserInfo', res)
    //   return res
    // },
    logout(context) {
      context.commit('setToken', '')
      removeToken()
      // context.commit('setUserInfo', {})
      // 重置路由
      resetRouter()
    }

  }
}
